const utils = require('@internal/scripts/utils')
const path2 = require('path')
const dayjs = require('dayjs')
const sfutils = require('sf-utils2')

const { isPlainObject, hasOwn } = sfutils

const getData = (data) => {
  if (isPlainObject(data) && hasOwn(data, 'code') && hasOwn(data, 'message')) {
    return data?.data || {}
  }
  return data
}

/**
 * 返回体封装
 * @param code
 * @param message
 * @param data
 * @return {{code: number, data: {}, message: string}}
 * @constructor
 */
function Result({ code = 200, message = 'ok', data = null }) {
  return { code, message, data: getData(data), responseId: sfutils.uuid(), responseTime: Number(new Date()) }
}

/**
 * 请求成功
 * @param data
 * @return {{code: number, data: {}, message: string}}
 */
Result.ok = (data) => new Result({ code: 200, data: getData(data) })

/**
 * 请求失败500
 * @param message
 * @return {{code: number, data: {}, message: string}}
 */
Result.err = (message) => new Result({ code: 500, data: null, message })

/**
 * 请求失败
 * @param code
 * @param message
 * @return {{code: number, data: {}, message: string}}
 */
Result.error = (code = 500, message = '服务端内部错误😅') => new Result({ code, data: null, message })

/**
 * 请求分页
 * @return {{code: number, data: {}, message: string}}
 */
Result.page = (opts = { dataList: [], mark: {} }) =>
  new Result({ data: { dataList: opts.dataList, mark: Result.mark(opts.mark) } })

/**
 * 分页
 * @param mark
 * @return {{current: number, totalSummarize: null, size: number, totalPageCount: number, totalRowCount: number, subtotalSummarize: null, currentRowCount: number}}
 */
Result.mark = (mark = {}) => {
  const page = {
    current: 1,
    size: 10,
    totalPageCount: 2,
    totalRowCount: 12,
    currentRowCount: 10,
    subtotalSummarize: null,
    totalSummarize: null
  }
  return {
    ...page,
    ...(mark || {})
  }
}

/**
 * 转化controllers 层
 * @param obj
 * @return {{}}
 */
Result.transformControllers = function (obj) {
  return Object.entries(obj).reduce((pre, [k, v]) => {
    if (sfutils.isFunction(v)) {
      pre[k] = async function (req, res) {
        try {
          await v.call(this, ...arguments)
        } catch (e) {
          console.log('错误信息:', e, '\n')
          res.send(Result.err(`错误信息：` + e.toString()))
        }
      }
    }
    return pre
  }, {})
}

/**
 * 当前项目根路径
 * @type {string}
 */
const ROOT_PATH = path2.join(__dirname, '../')

// 格式化日期
function formatDate(date = new Date(), format = 'YYYY-MM-DD HH:mm:ss') {
  return dayjs(date).format(format)
}

module.exports = {
  ...utils,
  formatDate,
  ROOT_PATH,
  Result
}
